<template>
  <div class="active">
    <el-form
      ref="formRef"
      :model="fileform"
      label-width="100px"
      label-position="top"
    >
      <el-form-item label="报名供应商名称">
        {{ fileform.name }}
      </el-form-item>
      <el-row>
        <el-col :span="11">
          <el-form-item label="报名时间">
            {{ fileform.applyTime }}
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="供应商编号">
            {{ fileform.supplierCode }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="报名人姓名">
            {{ fileform.supplierName }}
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="报名人电话">
            {{ fileform.supplierPhone }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="公司电子邮箱">
            {{ fileform.supplierEmail }}
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="参选人是否为制造商或下属子公司">
            <el-radio-group v-model="fileform.isFactory" disabled>
              <el-radio label="0">否</el-radio>
              <el-radio label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <h2 style="text-align: left">供应商资质审查文件</h2>
      <div
        class="sectionfile"
        v-for="(item, index) in fileform.Fileslist"
        :key="index"
      >
        <div class="section-title">{{ item.name }}</div>
        <div
          :span="6"
          v-for="(file, index) in item.list"
          :key="index"
          style="display: flex; align-items: end"
        >
          <img
            v-if="isPdf(item) == 'pdf'"
            src="@/assets/PDF.png"
            alt=""
            style="width: 140px; height: 140px"
          />
          <img
            v-else-if="isPdf(item) == 'png'"
            src="@/assets/PNG.png"
            alt=""
            style="width: 140px; height: 140px"
          />
          <img
            v-else-if="isPdf(item) == 'jpg'"
            src="@/assets/JPG.png"
            alt=""
            style="width: 140px; height: 140px"
          />
          <img
            v-else
            src="@/assets/zip.png"
            alt=""
            style="width: 140px; height: 140px"
          />
          <div
            style="
              display: flex;
              flex-direction: column;
              height: 140px;
              justify-content: start;
            "
          >
            <span
              @click="downloadFile(file)"
              class="link"
              style="padding-top: 10px"
              >下载</span
            >
            <span
              @click="previewFile(file)"
              class="link"
              style="padding-top: 10px"
              >预览</span
            >
          </div>
          <!-- {{ file.url }} -->
        </div>
      </div>

      <!-- <div v-if="!lock"> -->

      <div v-if="pattern != 'project_relative_price'">
        <div
          v-if="
            filePrice.length != 0 ||
            (usertype == 'judge_compere' && type == 'taskDecode')
          "
          class="section-title"
        >
          供应商报价参选文件
        </div>
        <el-row>
          <el-col :span="6">
            <UploadItem
              :fileList="filePrice"
              class="UploadItem"
              :action="`${baseUrl}/common/uploadProjectFile?projectCode=${projectCode}&projectId=${projectId}`"
              fileKey="certLevel"
              @onSuccess="handlePriceSuccess"
              @onRemove="handleRemove"
              @onPreview="handlePreview"
              :limit="1"
              :accept="'.pdf'"
              :uploadHeaders="Token"
              :type="'pdf'"
              Default="@/assets/PDF.png"
              :class="
                filePrice.length >= 1 || usertype != 'judge_compere'
                  ? 'close'
                  : ''
              "
            />
          </el-col>
        </el-row>
        <div v-if="filelist.length != 0" class="section-title">
          供应商资质参选文件
        </div>
        <el-row>
          <el-col :span="6">
            <UploadItem
              class="UploadItem"
              :action="`${baseUrl}/common/uploadProjectFile?projectCode=${projectCode}&projectId=${projectId}`"
              :fileList="filelist"
              fileKey="certLevel"
              @onSuccess="handleUploadSuccess"
              @onRemove="handleRemove"
              @onPreview="handlePreview"
              :limit="4"
              :accept="'.pdf'"
              :uploadHeaders="Token"
              :type="'pdf'"
              Default="@/assets/PDF.png"
              :class="
                filelist.length >= 4 || usertype != 'judge_compere'
                  ? 'close'
                  : ''
              "
            />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="参选文件密码">
              <el-input
                v-model="fileform.downloadPassword"
                :disabled="usertype != 'judge_compere' || type != 'taskDecode'"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="询问密码时间">
              <el-input v-model="fileform.downloadTime" disabled></el-input
              ><span></span>
              <el-button
                v-if="usertype == 'judge_compere' && type == 'taskDecode'"
                type="primary"
                @click="recordPassword"
                >记录</el-button
              >
              <!-- <el-button type="primary" @click="text">打印</el-button> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="type == 'taskDecode'">
          <el-col :span="11">
            <el-form-item label="异常情况">
              <el-input
                v-model="fileform.remark"
                :disabled="usertype != 'judge_compere' || type != 'taskDecode'"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="endbutton">
          <div
            v-if="
              usertype == 'judge_compere' && fileform.taskNode == 'taskDecode'
            "
          >
            <el-button type="primary" @click="confirmeditfilet"
              >保存并返回</el-button
            >
          </div>
          <div v-else>
            <el-button type="primary" @click="confirmedit">返回</el-button>
          </div>
        </div>
      </div>
      <div v-else>
        <h3>供应商报价参选文件</h3>
        <div
          :span="6"
          v-for="(file, index) in filelist"
          :key="index"
          style="display: flex; align-items: end"
        >
          <img
            v-if="isPdf(file) == 'pdf'"
            src="@/assets/PDF.png"
            alt=""
            style="width: 140px; height: 140px"
          />
          <img
            v-else-if="isPdf(item) == 'png'"
            src="@/assets/PNG.png"
            alt=""
            style="width: 140px; height: 140px"
          />
          <img
            v-else-if="isPdf(item) == 'jpg'"
            src="@/assets/JPG.png"
            alt=""
            style="width: 140px; height: 140px"
          />
          <img
            v-else
            src="@/assets/zip.png"
            alt=""
            style="width: 140px; height: 140px"
          />
          <div
            style="
              display: flex;
              flex-direction: column;
              height: 140px;
              justify-content: start;
            "
          >
            <span
              @click="downloadFile(file)"
              class="link"
              style="padding-top: 10px"
              >下载</span
            >
            <span
              @click="previewFile(file)"
              class="link"
              style="padding-top: 10px"
              >预览</span
            >
          </div>
          <!-- {{ file.url }} -->
        </div>
        <div class="endbutton">
          <div
            v-if="
              usertype == 'judge_compere' && fileform.taskNode == 'taskDecode'
            "
          >
            <el-button type="primary" @click="confirmeditfilet"
              >保存并返回</el-button
            >
          </div>
          <div v-else-if="back">
            <el-button type="primary" @click="confirmedit">返回</el-button>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { useRoute } from "vue-router";
import { judgeProjectInfo } from "@/api/project.js";
import { getDictList, getDict, nowTime } from "@/utils/common.js";
import {
  applySupplierInfo,
  updateApplySupplier,
  insertStoreFile,
  selectStoreFileList,
  queryTaskId,
  deleteStoreFileByIds,
} from "@/api/examine.js";
import UploadItem from "@/components/UploadItem.vue";
import { ElMessage } from "element-plus";

const route = useRoute();
const props = defineProps({
  id: {
    type: String,
    required: true,
  },
  type: {
    type: String,
    required: true,
  },
  judgeid: {
    type: String,
    required: true,
  },
  back: {
    type: String,
    required: true,
  },
  pattern: {
    type: String,
    required: true,
  },
});

const usertype = computed(
  () => JSON.parse(localStorage.getItem("judgeInfo")).type
);
const lock = ref(false);
const projectCode = ref("");
const projectId=ref("")
const fileform = ref({
  id: "",
  applyTime: "",
  supplierCode: "",
  name: "",
  supplierPhone: "",
  supplierEmail: "",
  isFactory: "",
  downloadPassword: "",
  downloadTime: "",
  remark: "",
  Fileslist: [],
  referlist: [],
});
const filelist = ref([]);
const filePrice = ref([]);
const token = localStorage.getItem("token");
const Token = computed(() => ({
  Authorization: token,
}));
const getInfo = () => {
  applySupplierInfo({ id: props.judgeid }).then((res) => {
    fileform.value = res.data;
    fileform.value.Fileslist = [];
    filelist.value = [];
    filePrice.value = [];

    if (fileform.value.isDownload == "1") lock.value = true;
    for (let i = 0; i < res.data.valueList.length; i++) {
      if (res.data.valueList[i].textValue && res.data.valueList[i].pushValue) {
        fileform.value.Fileslist[i] = {
          name: res.data.valueList[i].textValue,
          list: [
            {
              name: res.data.valueList[i].textValue,
              url: res.data.valueList[i].pushValue,
            },
          ],
        };
      } else {
        filelist.value.push({
          id: res.data.valueList[i].id,
          name: extractFileName(res.data.valueList[i].pushValue),
          url: res.data.valueList[i].pushValue,
          type: extractFileExtension(res.data.valueList[i].pushValue),
        });
      }
    }
    if (
      !fileform.value.downloadTime &&
      props.pattern == "project_relative_price"
    ) {
      recordPassword();
    }
    getList();
  });
  judgeProjectInfo({ id: props.id }).then((res) => {
    if (res.code == "200") {
      fileform.value.taskNode = res.data.taskNode;
      projectCode.value = res.data.oaCode;
      projectId.value=res.data.id
    }
  });
};
const getList = () => {
  selectStoreFileList({ applyId: fileform.value.id }).then((res) => {
    if (res.code == "200") {
      for (let i = 0; i < res.data.length; i++) {
        if (res.data[i].tableName == "store_apply_price") {
          let name = extractFileName(res.data[i].fileUrl);
          filePrice.value.push({
            id: res.data[i].id,
            name: name,
            url: res.data[i].fileUrl,
            type: extractFileExtension(res.data[i].fileUrl),
          });
        } else {
          let name = extractFileName(res.data[i].fileUrl);
          filelist.value.push({
            id: res.data[i].id,
            name: name,
            url: res.data[i].fileUrl,
            type: extractFileExtension(res.data[i].fileUrl),
          });
        }
      }
    }
  });
};
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const isPdf = (item) => {
  const url = item.url || item.list[0].url || "";
  const ext = url.split(".").pop().toLowerCase();
  return ext;
};
function extractFileName(url) {
  // 获取URL的最后一部分，即文件名加后缀
  const fileNameWithExtension = url.substring(url.lastIndexOf("/") + 1);

  // 去除文件名中的后缀
  const fileNameWithoutExtension = fileNameWithExtension
    .split(".")
    .slice(0, -1)
    .join(".");

  return fileNameWithoutExtension;
}
function extractFileExtension(url) {
  // 获取URL的最后一部分，即文件名加后缀
  const fileNameWithExtension = url.substring(url.lastIndexOf("/") + 1);

  // 检查是否包含"."以确定是否存在扩展名
  if (fileNameWithExtension.indexOf(".") === -1) {
    return ""; // 如果没有找到"."，则返回空字符串，表示没有扩展名
  }

  // 提取文件的后缀
  const fileExtension = fileNameWithExtension.split(".").pop(); // 使用 pop 获取数组的最后一个元素

  return fileExtension;
}

//下载项目
const downloadFile = async (file) => {
  let Url = "";
  if (file.url) {
    Url = file.url;
  } else {
    Url = file.fileUrl;
  }
  // Fetch the file data as a blob
  const response = await fetch(`${baseUrl}${Url}`);
  if (!response.ok) throw new Error("下载失败");

  const blob = await response.blob();
  const url = URL.createObjectURL(blob);

  // Create a temporary link for downloading
  const link = document.createElement("a");
  link.href = url;
  link.download = Url.split("/").pop(); // Extract file name
  link.click();

  // Revoke the URL after download
  URL.revokeObjectURL(url);
};
const recordPassword = () => {
  fileform.value.downloadTime = nowTime();
  fileform.value.isDownload = "1";
  confirmeditfilet();
};
const confirmeditfilet = () => {
  const params = {
    ...fileform.value,
  };
  delete params.Fileslist;
  delete params.valueList;

  updateApplySupplier(params).then((res) => {
    if (res.code == "200") {
      console.log("提交成功");
      // getInfo();
      window.close(); // 关闭当前页面
    }
  });
};
const confirmedit = () => {
  window.close(); // 关闭当前页面
};
const handlePriceSuccess = (response, fileKey, fileName) => {
  const params = {
    sourceId: fileform.value.id,
    projectId: fileform.value.projectId,
    fileUrl: fileName,
    tableName: "store_apply_price",
  };
  insertStoreFile(params).then((res) => {
    if (res.code == "200") {
      getInfo();
      // window.location.replace("");
    }
  });
};
const handleUploadSuccess = (response, fileKey, fileName) => {
  if (props.type != "taskDecode") {
    ElMessage({
      message: "无法操作",
      type: "error",
    });
    return;
  }
  const params = {
    sourceId: fileform.value.id,
    projectId: fileform.value.projectId,
    fileUrl: fileName,
    tableName: "store_apply_supplier",
  };
  insertStoreFile(params).then((res) => {
    if (res.code == "200") {
      getInfo();
      // window.location.replace("");
    }
  });
};
const handleRemove = (file, fileKey) => {
  if (file.type == "zip" || file.type == "rar") {
    ElMessage({
      message: "禁止删除",
      type: "error",
    });
    return;
  }
  if (usertype.value != "judge_compere") {
    ElMessage({
      message: "权限不足",
      type: "error",
    });
    return;
  }
  if (props.type != "taskDecode") {
    ElMessage({
      message: "无法操作",
      type: "error",
    });
    return;
  }
  // return
  deleteStoreFileByIds({ projectId: props.id, ids: file.id }).then((res) => {
    if (res.code == "200") getInfo();
  });
};
const handlePreview = (file) => {
  if (file.type == "zip" || file.type == "rar") {
    downloadFile(file);
    return;
  }
  previewFile(file);
};

const generatePreviewUrl = (path) => {
  // 确保路径正确，适配后端服务地址
  const baseUrl = import.meta.env.VITE_APP_BASE_API;
  return `${baseUrl}${path}`;
};
const previewFile = (file) => {
  const url = generatePreviewUrl(file.url);
  window.open(url, "_blank");
};
// 定义表格数据
onMounted(() => {
  getInfo();
});
</script>

<style scoped lang="scss">
@use "./judge";
:deep(.UploadItem .el-upload-list--picture-card) {
  flex-wrap: nowrap;
}
:deep(.upload-demo.UploadItem.close) {
  position: relative;
  height: 140px;
}
:deep(.UploadItemRow) {
  height: 150px;
}

:deep(.close .el-upload) {
  display: none;
}
</style>
